package models

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/fwhezfwhez/errorx"
)

type User struct {
	Id            string `orm:"column(id);pk;size(64)" json:"id" form:"id"`
	Mobile        int64  `orm:"column(mobile)" json:"mobile" form:"mobile"`
	Password      string `orm:"column(password)" json:"-" form:"password"`
	CreateTime    int64  `orm:"column(create_time)" json:"create_time" form:"create_time"`
	LastLoginTime int    `orm:"column(last_login_time)" json:"last_login_time" form:"last_login_time"`
	LastLoginIp   int    `orm:"column(last_login_ip)" json:"last_login_ip" form:"last_login_ip"`
	Status        int    `orm:"column(status)" json:"status" form:"status"`
	NickName      string `orm:"column(nick_name)" json:"nick_name" form:"nick_name"`
	Birthday      string `orm:"column(birthday)" json:"birthday" form:"birthday"`
	Sex           int    `orm:"column(sex)" json:"sex" form:"sex"`
	Avatar        string `orm:"column(avatar)" json:"avatar" form:"avatar"`
}

func init() {
	orm.RegisterModel(new(User))
}

func (m *User) TableName() string {
	return "user"
}

// 根据id获取用户数据
func GetUserById(id string) (*User, error) {
	data := &User{Id: id}
	if err := orm.NewOrm().Read(data); err != nil {
		if err == orm.ErrNoRows {
			return nil, nil
		}
		return nil, errorx.New(err)
	}

	return data, nil
}

// 获取用户列表
// @return lists 用户列表
// @return count 符合条件的总数据量
// @return err error
func GetUserLists(wheres map[string]interface{}, page int64) (lists []*User, count int64, err error) {
	qs := orm.NewOrm().QueryTable(new(User).TableName())

	if len(wheres) > 0 {
		for name, value := range wheres {
			qs = qs.Filter(name, value)
		}
	}

	if page < 1 {
		page = 1
	}

	// 符合条件的总条数
	count, err = qs.Count()
	if err != nil {
		return nil, 0, errorx.New(err)
	}
	if count == 0 {
		return nil, 0, nil
	}

	// 每页限制数量
	offset := beego.AppConfig.DefaultInt64("page_offset_number", 20)
	start := (page - 1) * offset
	num, err := qs.Limit(start).Offset(offset).All(&lists)
	if err != nil {
		return nil, 0, errorx.New(err)
	}
	if num == 0 {
		return nil, 0, nil
	}

	return lists, count, nil
}
